package uploader

import (
	"github.com/google/uuid"
	"io"
	"log"
	"os"
	"path/filepath"
	"server/business/config"
	"server/business/errors/common_errors"
	file2 "server/business/file_server2/file"
	"server/framework/web/context"
)

type DirectUploader struct {
	filePath string
}

func (d *DirectUploader) HandleUpload(c *context.Context) {
	file, fileHeader, err := c.R.FormFile("file")

	if err != nil {
		c.RespBadRequest(common_errors.FieldFileNotFound.Error())
		return
	}

	fid := uuid.New().String()
	ext := filepath.Ext(fileHeader.Filename)
	config.FileStorage[fid+ext] = fileHeader.Filename

	path := filepath.Join(d.filePath, fid+ext)
	var dst *os.File
	dst, err = os.Create(path)
	if err != nil {
		log.Println(err.Error())
		c.RespSystemErr(common_errors.UploadError.Error())
		return
	}

	_, err = io.Copy(dst, file)
	if err != nil {
		log.Println(err.Error())
		c.RespSystemErr(common_errors.UploadError.Error())
		return
	}
	c.RespOk(&file2.FileMeta{
		Fid:  fid,
		Name: fileHeader.Filename,
	})

	defer func() {
		_ = file.Close()
		_ = dst.Close()
	}()
}

func NewDirectUploader(path string) *DirectUploader {
	return &DirectUploader{
		filePath: path,
	}
}
